package com.hyz.service.impl;

import client.AssetClient;
import client.LogClient;
import client.UserClient;
import com.hyz.pojo.ResponseResult;
import com.hyz.pojo.assetSecondment.AssetSecondmentRequest;
import com.hyz.pojo.assetSecondment.AssetSecondmentResponse;
import com.hyz.service.ApproveService;
import com.hyz.util.Conversion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.log.IsComplete;
import pojo.log.assetSecondment.AssetSecondment;
import pojo.log.assetSecondment.AssetSecondmentResultEnum;
import pojo.log.assetSecondment.AssetSecondmentStatusEnum;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HGD
 * @date 2022/10/5 14:20
 */
@Service
public class ApproveServiceImpl implements ApproveService {
    @Autowired
    private LogClient logClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private AssetClient assetClient;
    @Autowired
    private Conversion conversion;

    @Override
    public ResponseResult<List<AssetSecondmentResponse>> apGetAssetSecondments() {
        // TODO: 获取用户id
        Long approveId = 1L;
        Long departmentId = userClient.getDepartmentIddById(approveId);
        // 获取部门所有人id
        List<Long> applicantIds = userClient.getIdsByDepartmentId(departmentId);

        // 获取资产借用申请
        List<AssetSecondment> assetSecondments = new ArrayList<>();
        for (Long applicantId : applicantIds) {
            AssetSecondment assetSecondment = AssetSecondment.builder()
                    .applicantId(applicantId)
                    .status(AssetSecondmentStatusEnum.BORROW)
                    .result(AssetSecondmentResultEnum.CREATE)
                    .isComplete(IsComplete.UNFINISHED).build();
            assetSecondments.addAll(logClient.getAssetSecondments(assetSecondment));
        }
        List<AssetSecondmentResponse> responses = conversion.getAssetSecondmentResponse(assetSecondments);
        return new ResponseResult<>(200, "成功", responses);
    }

    @Override
    public ResponseResult<List<AssetSecondmentResponse>>
    apUpdateAssetSecondment(AssetSecondmentRequest request) {
        Long id = request.getId();
        Boolean result = request.getResult();
        if (id == null || result == null) {
            return new ResponseResult<>(500, "参数缺失");
        }
        AssetSecondment assetSecondment = new AssetSecondment();
        assetSecondment.setId(id);
        assetSecondment.setResult(result ?
                AssetSecondmentResultEnum.APPROVAL_AGREE :
                AssetSecondmentResultEnum.FAILED);
        assetSecondment.setIsComplete(result ?
                IsComplete.UNFINISHED :
                IsComplete.COMPLETE);

        if (logClient.updateAssetSecondmentById(assetSecondment)) {
            return apGetAssetSecondments();
        }
        return new ResponseResult<>(500, "操作失败，请稍后再尝试");
    }
}
